package com.example.springboot.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.example.springboot.controller.request.BaseRequest;
import com.example.springboot.entity.Staff;
import com.example.springboot.exception.ServiceException;
import com.example.springboot.mapper.StaffMapper;
import com.example.springboot.service.IStaffService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

//使用指定类初始化日志对象，在日志输出的时候，可以打印出日志信息所在的类
@Slf4j
@Service
//@Service注解将StaffService转为spring的一个组件
public class StaffService implements IStaffService {

    @Autowired //通过autowired导入staffMapper
    StaffMapper staffMapper;

    private static final String DEFAULT_PASS="123";
    private static final String PASS_SALT="sixia";

    @Override
    public List<Staff> list() {
//        有时需要try catch处理来解决函数存在的问题
        return staffMapper.list();
    }

    @Override
    public PageInfo<Staff> page(BaseRequest baseRequest){
//        dependency引入pagehelper
//        PageHelper传入页面和每页信息条数
        PageHelper.startPage(baseRequest.getPageNum(),baseRequest.getPageSize());
        List<Staff> staffs=staffMapper.listByCondition(baseRequest);
        return new PageInfo<>(staffs);
    }

    @Override
    public void save(Staff staff){//        当做卡号来处理
        Date date= new Date();
//     通过hashCode编码将fastSimpleUUID产生的字母和数字转为数字
        staff.setNickName(DateUtil.format(date,"yyyyMMdd")+Math.abs(IdUtil.fastSimpleUUID().hashCode()));
        if(StrUtil.isBlank(staff.getPassword())){
            staff.setPassword(DEFAULT_PASS);
        }
        staff.setPassword(securePass(staff.getPassword()));//设置md5加密
        try{
            staffMapper.save(staff);
        }catch(DuplicateKeyException e){
            log.error("数据插入失败,nickName:{}",staff.getNickName());
            throw new ServiceException("用户插入失败");
        }
    }

    //  通用代码封装 md5加密
    private String securePass(String password){
        return SecureUtil.md5(password+PASS_SALT);
    }

    @Override
    public Staff getById(Integer id) {
        return staffMapper.getById(id);
    }

    @Override
    public void update(Staff staff) {
        staff.setUpdateTime(new Date());
        staffMapper.updateById(staff);

    }

    @Override
    public void deleteById(Integer id) {
        staffMapper.deleteById(id);
    }

}
